import HtmlLink from '@/app/components/common/html-link';
import VideoCard from '@/app/components/video-list/video-card';
import VipOnlyTip from '@/app/components/vip/vip-only-tip';
import '@/app/drawer.css';
import { generateDetailMetadata } from '@/lib/utils/metadata';
import { formatDate, formatPlayCount, parsePlayUrl } from '@/lib/utils/utils';
import { VideoService } from '@/lib/video/video-service';
import type { Metadata } from 'next';
import Image from 'next/image';
import HistoryListener from '@/app/components/common/history-listener';
import VideoContainer from '@/app/components/video/video-container';

interface DetailPageProps {
  params: Promise<{
    slug: string[];
  }>;
}

// 生成动态元数据
export async function generateMetadata(
  props: DetailPageProps
): Promise<Metadata> {
  // 解构并获取参数
  const params = await props.params;
  
  // 解析路径参数获取ID
  const pathString = params.slug?.[0] || '';
  const [idStr] = pathString.split('-');
  const videoId = parseInt(idStr, 10);

  // 使用已缓存的VideoService方法获取视频信息
  const video = await VideoService.getVideoDetail(videoId);

  // 如果ID无效或视频不存在，返回默认元数据
  if (!video) {
    return {
      title: '视频不存在 - YZZY影视资源',
      description: 'YZZY影视资源网提供最新电影、电视剧、综艺、动漫等优质资源，内容丰富，画质清晰。',
    };
  }

  // 使用统一的元数据生成函数
  return generateDetailMetadata(
    video.vodName,
    video.vodContent || '',
    video.typeName || video.type?.name,
    video.vodRemarks || '',
    video.vodPic || '',
    video.vodActor || '',
    video.vodDirector || ''
  );
}

export default async function DetailPage(props: DetailPageProps) {
  // 解构并获取参数
  const params = await props.params;
  const slugPath = params.slug || [];
  
  // 解析路径参数获取ID
  const pathString = slugPath[0] || '';
  const [idStr] = pathString.split('-');
  const videoId = parseInt(idStr, 10);
  const episodeIndex = pathString.includes('-') ? parseInt(pathString.split('-')[1], 10) : 0;

  // 确保ID是有效的整数
  if (isNaN(videoId)) {
    return (
      <div className="text-center py-16">
        <h1 className="text-2xl font-bold mb-4">无效的视频ID</h1>
        <p className="text-gray-400">请提供有效的视频ID。</p>
        <div className="mt-8">
          <HtmlLink
            href="/"
            className="px-6 py-3 bg-red-600 text-white font-medium rounded-lg hover:bg-red-700 transition"
          >
            返回首页
          </HtmlLink>
        </div>
      </div>
    );
  }

  // 直接使用已缓存的VideoService方法
  const video = await VideoService.getVideoDetail(videoId);

  // 如果视频不存在
  if (!video) {
    return (
      <div className="text-center py-16">
        <h1 className="detail-title text-2xl font-bold mb-4">视频不存在</h1>
        <p className="detail-content text-gray-400">您访问的视频不存在或已被删除。</p>
        <div className="mt-8">
          <HtmlLink
            href="/"
            className="px-6 py-3 bg-red-600 text-white font-medium rounded-lg hover:bg-red-700 transition"
          >
            返回首页
          </HtmlLink>
        </div>
      </div>
    );
  }

  // 检查视频是否需要VIP权限
  if (video.noAccess) {
    return <VipOnlyTip message="该视频仅对VIP用户开放，请升级会员后观看" />;
  }

  // 解析播放地址
  const playList = parsePlayUrl(video.vodPlayUrl || null);

  // 确保选集索引有效
  const validEpisodeIndex = episodeIndex >= 0 && episodeIndex < playList.length
    ? episodeIndex
    : 0;

  // 获取相关推荐
  const relatedVideos = await VideoService.getRelatedVideos(video.typeId, video.id, 12);

  // 获取顶级分类ID
  const topCategoryId = video.type.parentId || video.type.id;

  return (
    <div className="container mx-auto sm:px-6 md:px-8 lg:px-12 xl:px-20 2xl:px-24 sm:py-3 sm:pb-4 max-w-full overflow-x-hidden" data-top-category-id={topCategoryId} data-actual-type-id={video.typeId}>
      <div className="sm:pb-12">
        {/* 面包屑导航 */}
        <div className="max-sm:hidden flex items-center text-[14px] sm:text-base text-gray-400 pb-3">
          <HtmlLink href="/" className="detail-meta hover:text-white">首页</HtmlLink>
          <span className="mx-2">/</span>
          <HtmlLink 
            href={video.type.parentId ? `/type/${video.type.parentId}?type=${video.type.id}` : `/type/${video.type.id}`} 
            className="detail-meta hover:text-white"
          >
            {video.type.name}
          </HtmlLink>
          <span className="mx-2">/</span>
          <span className="text-white truncate max-w-[75%] detail-meta">{video.vodName}</span>
        </div>

        {/* 历史监听器 */}
        {playList.length > 0 && <HistoryListener playList={playList} />}

        {/* 视频播放区域 */}
        {playList.length > 0 && (
          <VideoContainer
            playList={playList}
            initialIndex={validEpisodeIndex}
            videoId={video.id}
          />
        )}

        <div className="max-sm:px-3">
        {/* 视频信息 */}
        <div className="flex flex-col md:flex-row gap-8 mb-2 md:mb-3 lg:mb-6">
          {/* 封面图 */}
          <div className="hidden md:block w-1/2 mx-auto md:mx-0 md:w-48 flex-shrink-0">
            <div className="relative aspect-[3/4] w-full overflow-hidden rounded-lg shadow-lg">
              <Image
                src={video.vodPic || '/images/placeholder.jpg'}
                alt={video.vodName}
                fill
                sizes="(max-width: 768px) 50vw, 20vw"
                className="object-cover"
                priority
              />

              {/* 评分 */}
              {video.vodScore && video.vodScore > 0 && (
                <div className="absolute top-3 right-3 bg-red-600 text-white font-bold px-3 py-1 rounded-full text-lg z-10">
                  {video.vodScore.toFixed(1)}
                </div>
              )}
            </div>

            {/* 播放信息 */}
            <div className="flex justify-between items-center mt-4 text-gray-300 text-[14px] sm:text-base">
              <div className="flex items-center">
                <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                </svg>
                <span>{formatPlayCount(video.vodHits || 0)}</span>
              </div>
              <div>
                {formatDate(video.vodTime)}
              </div>
            </div>
          </div>

          {/* 详细信息 */}
          <div className="flex-grow">
            <h1 className="detail-title text-2xl md:text-3xl font-bold mb-4">{video.vodName}</h1>

            {/* {video.vodEnname && (
              <div className="detail-meta text-gray-400 mb-4 hidden md:block">{video.vodEnname}</div>
            )} */}

            {video.vodRemarks && (
              <div className="detail-meta inline-block px-3 py-1 bg-background-dark text-white text-[14px] sm:text-base rounded-full mb-4">
                {video.vodRemarks}
              </div>
            )}

            <div className="grid grid-cols-3 md:grid-cols-3 gap-y-3 gap-x-4 mb-8">
              {video.vodYear && (
                <div className="flex items-start">
                  <span className="detail-meta text-gray-400 mr-2 w-10 md:w-12  shrink-0 text-[14px] sm:text-base">年份:</span>
                  <span className="detail-meta text-[14px] sm:text-base">{video.vodYear}</span>
                </div>
              )}

              {video.typeName && (
                <div className="flex items-start">
                  <span className="detail-meta text-gray-400 mr-2 w-10 md:w-12  shrink-0 text-[14px] sm:text-base">类型:</span>
                  <span className="detail-meta text-[14px] sm:text-base">{video.typeName}</span>
                </div>
              )}

              {video.vodArea && (
                <div className="flex items-start">
                  <span className="detail-meta text-gray-400 mr-2 w-10 md:w-12  shrink-0 text-[14px] sm:text-base">地区:</span>
                  <span className="detail-meta text-[14px] sm:text-base">{video.vodArea}</span>
                </div>
              )}

              {video.vodDirector && (
                <div className="flex items-start md:col-span-1 max-sm:col-span-3">
                  <span className="detail-meta text-gray-400 mr-2 w-10 md:w-12  shrink-0 text-[14px] sm:text-base">导演:</span>
                  <span className="detail-meta flex-grow text-[14px] sm:text-base">{video.vodDirector}</span>
                </div>
              )}

              {video.vodActor && (
                <div className="flex items-start md:col-span-2 max-sm:col-span-3">
                  <span className="detail-meta text-gray-400 mr-2 w-10 md:w-12  shrink-0 text-[14px] sm:text-base">主演:</span>
                  <span className="detail-meta flex-grow text-[14px] sm:text-base">{video.vodActor}</span>
                </div>
              )}

              {video.vodLang && (
                <div className="flex items-start">
                  <span className="detail-meta text-gray-400 mr-2 w-10 md:w-12  shrink-0 text-[14px] sm:text-base">语言:</span>
                  <span className="detail-meta text-[14px] sm:text-base">{video.vodLang}</span>
                </div>
              )}
            </div>


          </div>
        </div>
        {/* 剧情简介 */}
        <div className="mb-12 max-sm:mb-12">
          <h3 className="text-lg font-semibold mb-2 flex items-center">
            <span className="w-1 h-5 bg-red-600 rounded-sm mr-2"></span>
            剧情简介
          </h3>
          <div className="text-gray-300 leading-relaxed text-[14px] sm:text-base">
            {video.vodContent || "暂无简介"}
          </div>
        </div>


        {/* 相关推荐 */}
        {relatedVideos.length > 0 && (
          <div>
            <h2 className="text-xl font-bold mb-4 flex items-center">
              <span className="w-1 h-6 bg-red-600 rounded-sm mr-2"></span>
              相关推荐
            </h2>
            <div className="grid grid-cols-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-2 sm:gap-4 md:gap-6 mb-8 sm:mb-0">
              {relatedVideos.map((video) => (
                <VideoCard key={video.id} video={video} />
              ))}
            </div>
          </div>
        )}
        </div>
      </div>
    </div>
  );
} 